package com.shijunhao.graduation.utils;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shijunhao.graduation.exception.BusinessException;
import com.shijunhao.graduation.properties.DefaultParams;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author: shijunhao
 * @date: 2022/3/6 23:04
 * @description:
 */
public class PageUtils {


    /**
     * @return: com.baomidou.mybatisplus.extension.plugins.pagination.Page<T>
     * @author: shijunhao
     * @date: 2022/3/6 23:32
     * @description: 通过request获取当前分页的请求页数及大小
     */
    public static <T> Page<T> getPage() {
        HttpServletRequest request = ServletUtils.getRequest();
        String pageNo = request.getParameter(DefaultParams.PAGE_NO);
        String pageNum = request.getParameter(DefaultParams.PAGE_NUM);
        Page<T> page = new Page<>();
        try {
            long lPageNo = Long.parseLong(pageNo);
            long lPageNum = Long.parseLong(pageNum);
            page.setCurrent(lPageNo);
            page.setSize(lPageNum);
        } catch (NumberFormatException e) {
            throw new BusinessException("分页参数错误！");
        }
        return page;
    }

    /**
     * @param records: 现有的记录
     * @return: com.baomidou.mybatisplus.extension.plugins.pagination.Page<T>
     * @author: shijunhao
     * @date: 2022/3/6 23:33
     * @description: 将当前现有的数据封装成page对象 todo 待测试
     */
    public static <T> Page<T> getPage(List<T> records) {
        Page<T> page = getPage();
        //设置大小，总数
        page.setTotal(records.size());
        page.setPages(records.size() % page.getSize() == 0 ? records.size() / page.getSize() : records.size() / page.getSize() + 1);
        List<T> recordsNew = new ArrayList<>();
        //将对应位置的元素封装到page中
        for (int i = 0; i < page.getSize() && i < records.size(); i++) {
            long currentIdx = (page.getCurrent()-1) * page.getSize() + i;
            recordsNew.add(records.get((int) currentIdx));
        }
        page.setRecords(recordsNew);
        return page;
    }

    /**
     * @return: com.baomidou.mybatisplus.extension.plugins.pagination.Page<T>
     * @author: shijunhao
     * @date: 2022/4/9 21:49
     * @description: 获得一个初始化数量为10的分页
     */
    public static <T> Page<T> initPage(){
        Page<T> page = new Page<>();
        page.setCurrent(1);
        page.setSize(DefaultParams.DEFAULT_PAGE_SIZE);
        return page;
    }
}
